package com.thanks.thinkchina.modules.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.thanks.thinkchina.modules.entity.vo.ExchangeRateVo;
import com.thanks.thinkchina.modules.service.ExchangeRateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName : ExchangeRateServiceImpl
 * @Description : ExchangeRate Service Implementation class
 * @Author : yf.zhu
 * @Date: 2022-04-17 11:42
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExchangeRateServiceImpl implements ExchangeRateService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * rate
     * @param target
     * @param symbols
     * @return
     */
    @Override
    public ExchangeRateVo rate(String target, String symbols) {
        /**
         * 整体逻辑：
         *      考虑到并发因素，所以先走缓存之后在走数据库检索
         *      如果走数据库检索并更新缓存数据
         */
        String key = target + "_" + symbols;
        log.info("rate mehtod key value is {}",key);
        Object value = redisTemplate.opsForValue().get(key);
        if (ObjectUtil.isNotEmpty(value)){
            log.debug("cache rate value is {}",value);
            return ExchangeRateVo.builder().rate(new BigDecimal(value.toString())).build();
        }
        // 走数据库检索并更新缓存数据

        this.redisTemplate.opsForValue().set(key,value,5, TimeUnit.MINUTES);
        return null;
    }

}
